#include "PatchStomper/StomperModel.h"
#include "StomperLib/Objects/RectPatchObject.h"
#include <sstream>
namespace PatchStomper
{
StomperModel::StomperModel( Gwen::Controls::Base* base ) : StomperLib::ToolModel( base )
{
  this->GridActive = false;

  TextureSize = StompedReality::Math::Vector2( 0, 0 );
  this->NextSuffix = 0;
  this->NextPatchID = 0;
  this->NextTextureID = 0;
  this->CurrentTextureInfo = NULL;
}

StomperModel::~StomperModel( ) {
}

bool StomperModel::Add( StompedReality::Math::Vector2 pos, StompedReality::Math::Vector2 size )
{
  if (this->ObjectList->Contains([&]( StomperLib::EditorObjectInfo* obj )->bool
                                 {
                                   auto patchObj = (StomperLib::RectPatchObject*) obj;
                                   return patchObj->Size.Equals( size ) && patchObj->Pos.Equals( pos );
                                 } ))
  {
    return false;
  }

  int s = this->CurrentWorkingFile.find_last_of( "/" )+1;
  int e = this->CurrentWorkingFile.find_first_of( "." );
  std::string patchBaseName = this->CurrentWorkingFile.substr( s, e-s );
  std::stringstream sstream;
  sstream << patchBaseName;
  sstream << "_";
  sstream << NextSuffix;

  auto obj = new StomperLib::RectPatchObject( );
  obj->Pos = pos;
  obj->Size = size;
  obj->Name = sstream.str( );
  obj->PatchID = this->NextPatchID;
  obj->TextureFile = this->CurrentWorkingFile;
  obj->TextureID = this->CurrentTextureInfo->ID;

  this->ObjectList->Add( obj );
  this->NotifyModification( this->CurrentWorkingFile );

  ++NextSuffix;
  ++NextPatchID;

  return true;
}

void StomperModel::Clear( )
{
  ObjectList->Clear( );
  this->NextSuffix = 0;
  this->NextPatchID = 0;
  this->NextTextureID = 0;
  this->CurrentTextureInfo = NULL;
  this->CurrentWorkingFile = "";
}

}